import time
from collections import OrderedDict
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.efficientnet import efficientnetv2_l


def conv3x3(in_planes, out_planes, stride=1, dilation=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, dilation=dilation, bias=False)
class PoolATT_S48(nn.Module):
    def __init__(self, inplanes):
        super(PoolATT_S48, self).__init__()
        midplanes = inplanes//4
        self.pool1 = nn.Sequential(
            nn.AvgPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.AvgPool2d(kernel_size=2, stride=2,ceil_mode=False)
        )
        self.pool2 = nn.Sequential(
            nn.AvgPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.AvgPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.AvgPool2d(kernel_size=2, stride=2,ceil_mode=False)
        )
        self.pool3 = nn.Sequential(
            nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=False)
        )
        self.pool4 = nn.Sequential(
            nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=False),
            nn.MaxPool2d(kernel_size=2, stride=2,ceil_mode=False)
        )
        self.ip = inplanes//4

        self.act = nn.ReLU(inplace=True)

        self.conv_1 = nn.Sequential(
            nn.Conv2d(midplanes, midplanes, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(midplanes , momentum=0.1),
        )
        self.conv_2 = nn.Sequential(
            nn.Conv2d(midplanes, midplanes, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(midplanes , momentum=0.1),

        )
        self.conv_3 = nn.Sequential(
            nn.Conv2d(midplanes, midplanes, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(midplanes , momentum=0.1),

        )
        self.conv_4 = nn.Sequential(
            nn.Conv2d(midplanes, midplanes, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(midplanes , momentum=0.1),
        )

    def forward(self, x):
        x1,x2,x3, x4 = torch.split(x, self.ip, dim=1)
        x1 = F.interpolate(self.conv_1(self.pool1(x1)), scale_factor=4, mode='bilinear', align_corners=False)
        x2 = F.interpolate(self.conv_2(self.pool2(x2)), scale_factor=8, mode='bilinear', align_corners=False)
        x3 = F.interpolate(self.conv_3(self.pool3(x3)), scale_factor=4, mode='bilinear', align_corners=False)
        x4 = F.interpolate(self.conv_4(self.pool4(x4)), scale_factor=8, mode='bilinear', align_corners=False)
        return torch.sigmoid(torch.cat([x1,x2,x3,x4],dim=1))*x




class R2DliaBlock(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1,image_size= (960, 640), scale_factor=0):
        super(R2DliaBlock, self).__init__()
        self.downsample = downsample
        self.relu = nn.ReLU(inplace=True)
        self.width = inplanes*scale_factor
        self.ip = self.width//4
        if self.downsample is not None:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, self.width ,kernel_size=3,  stride=2, padding=1, bias=False),
                nn.BatchNorm2d(self.width ),
                nn.ReLU(inplace=True),
            )
        else:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, self.width, kernel_size=3, stride=1, padding=1, bias=False),
                nn.BatchNorm2d(self.width),
                nn.ReLU(inplace=True)
            )


        self.conv1 = nn.Sequential(
            nn.Conv2d(self.ip , self.ip , kernel_size=1, padding=0, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(self.ip , self.ip , kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=3, padding=2,dilation=2, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv4 = nn.Sequential(
            nn.Conv2d(self.ip , self.ip , kernel_size=3, padding=3, dilation=3, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv_out = nn.Sequential(
            nn.Conv2d(self.width, planes, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(planes),
        )

        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv0(x)
        x1, x2, x3, x4 = torch.split(out, self.ip, dim=1)
        x1 = self.conv1(x1)
        x2 = self.conv2(x1+x2)
        x3 = self.conv3(x2+x3)
        x4 = self.conv4(x3+x4)
        out = torch.cat([x1, x2, x3, x4], dim=1)
        out = self.conv_out(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out

class R2Block(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1,image_size= (960, 640), scale_factor=0):
        super(R2Block, self).__init__()
        self.downsample = downsample
        self.relu = nn.ReLU(inplace=True)
        self.width = inplanes*scale_factor
        self.ip = self.width//4
        if self.downsample is not None:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, self.width ,kernel_size=3,  stride=2, padding=1, bias=False),
                nn.BatchNorm2d(self.width ),
                nn.ReLU(inplace=True),
            )
        else:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, self.width, kernel_size=3, stride=1, padding=1, bias=False),
                nn.BatchNorm2d(self.width),
                nn.ReLU(inplace=True)
            )


        self.conv1 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, padding=1, stride=1),
            nn.Conv2d(self.ip , self.ip , kernel_size=1, padding=0, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(self.ip , self.ip , kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv4 = nn.Sequential(
            nn.Conv2d(self.ip , self.ip , kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(self.ip , momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv_out = nn.Sequential(
            nn.Conv2d(self.width, planes, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(planes),
        )

        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv0(x)
        x1, x2, x3, x4 = torch.split(out, self.ip, dim=1)
        x1 = self.conv1(x1)
        x2 = self.conv2(x1+x2)
        x3 = self.conv3(x2+x3)
        x4 = self.conv4(x3+x4)
        out = torch.cat([x1, x2, x3, x4], dim=1)
        out = self.conv_out(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out

class R2BlockCat(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1,image_size= (960, 640), scale_factor=0):
        super(R2BlockCat, self).__init__()
        self.downsample = downsample
        self.relu = nn.ReLU(inplace=True)
        self.factor = scale_factor
        self.ip = inplanes * self.factor // 4
        if self.downsample is not None:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, inplanes * self.factor,kernel_size=3,  stride=2, padding=1, bias=False),
                nn.BatchNorm2d(inplanes * self.factor),
                nn.ReLU(inplace=True)
            )
        else:
            self.conv0 = nn.Sequential(
                nn.Conv2d(inplanes, inplanes * self.factor, kernel_size=3, stride=1, padding=1, bias=False),
                nn.BatchNorm2d(inplanes * self.factor),
                nn.ReLU(inplace=True)
            )

        self.conv1 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=1, padding=0, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=5, padding=2, groups=2, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv4 = nn.Sequential(
            nn.Conv2d(self.ip, self.ip, kernel_size=7, padding=3, groups=4, bias=False),
            nn.BatchNorm2d(self.ip, momentum=0.1),
            nn.ReLU(inplace=True)
        )
        self.conv_out = nn.Sequential(
            nn.Conv2d(inplanes * self.factor, planes, kernel_size=1, stride=1, padding=0, bias=False),
            nn.BatchNorm2d(planes),
        )
        self.pool = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)

        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv0(x)
        x1, x2, x3, x4 = torch.split(out, self.ip, dim=1)
        x1 = self.conv1(x1)
        x2 = self.conv2(x2+x1)
        x3 = self.conv3(x3+x2)
        x4 = self.conv4(x4+x3)
        out = torch.cat([x1, x2, x3, x4], dim=1)
        out = self.conv_out(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out



class XagBlock(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1,image_size= (960, 640), scale_factor=0):
        super(XagBlock, self).__init__()

        self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation)
        self.bn1 = nn.BatchNorm2d(planes , momentum=0.1)
        self.relu = nn.ReLU()

        self.conv2 = conv3x3(planes, planes, stride=1, dilation=dilation)
        self.bn2 = nn.BatchNorm2d(planes , momentum=0.1)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)

        return out

class DslBlock(nn.Module):
    expansion = 1
    def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1,image_size= (960, 640), scale_factor=0):
        super(DslBlock, self).__init__()
        self.relu = nn.ReLU()
        self.conv1 = nn.Sequential(
            nn.Conv2d(inplanes, inplanes,kernel_size=3, padding=1, stride=stride, dilation=dilation),
            nn.BatchNorm2d(inplanes, momentum=0.1),
            nn.ReLU()
        )

        self.conv2 = nn.Sequential(
            nn.Conv2d(inplanes, planes*4, kernel_size=1, padding=0, stride=1, dilation=dilation),
            nn.BatchNorm2d(planes*4, momentum=0.1),
            nn.ReLU()
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(planes*4, planes, kernel_size=1, padding=0, stride=1, dilation=dilation),
            nn.BatchNorm2d(planes, momentum=0.1),
        )
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.conv2(out)
        out = self.conv3(out)
        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)

        return out

class ResNet(nn.Module):
    def __init__(self, block, layers=(3, 4, 23, 3), image_size=(960, 640)):
        self.inplanes = 64
        self.image_size = image_size
        super(ResNet, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(64 , momentum=0.1),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(64 , momentum=0.1),
            nn.ReLU(inplace=True),
        )
        self.layer1 = self._make_layer(XagBlock, 64, layers[0], scalefactor=1)
        self.layer2 = self._make_layer(XagBlock, 128, layers[1], stride=2, scalefactor=1)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2, scalefactor=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2, scalefactor=1)
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
    def _make_layer(self, block, planes, blocks, stride=1, dilation=1, scalefactor = None):
        downsample = None

        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion , momentum=0.1),
            )

        layers = [block(self.inplanes, planes, stride, downsample, 1, self.image_size,  scalefactor)]
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes, dilation=dilation, image_size = self.image_size, scale_factor=scalefactor))

        return nn.Sequential(*layers)

    def forward(self, x):
        x1 = self.conv1(x)
        x1 = self.layer1(x1)
        x2 = self.layer2(x1)
        x3 = self.layer3(x2)
        x4 = self.layer4(x3)
        return x1,x2,x3,x4



def resnet_xag_18(image_size=(960, 640)):
    model = ResNet(R2DliaBlock, [2, 2, 4, 2],image_size=(960, 640))
    return model
def resnet_xag_20():
    model = ResNet(R2Block, [1, 2, 4, 2])
    return model
def resnet_xag_34():
    model = ResNet(R2Block, [3, 4, 6, 3])
    return model

if __name__ == '__main__':
    md = resnet_xag_18()
    print(md)

    x = torch.randn(1,3 ,256, 256)
    md(x)
